let logger = G.logUtils.getLogger(__filename);

let userController = {
    findUser(deviceId) {
        let sql = `select * from user where device_id = '${deviceId}';`;
        return G.dbUtils.get(sql);
    },

    findUserByUserId(userId){
        let sql = `select * from user where user_id = ${userId};`;
        return G.dbUtils.get(sql);
    },

    newUser(deviceId, sysBushu) {
        let name = `游客${Date.now()}`;
        let dayTime = G.getDayStamp();
        let sql = `insert into user (name,last_sign_time,sys_bushu,device_id,sync_daytime) values ('${name}','${Date.now()}',${sysBushu},'${deviceId}','${dayTime}');`;
        return G.dbUtils.run(sql);
    },

    updateUserBuShu(user){
        let sql = `update user set bushu = ${user.bushu},sys_bushu = ${user.sys_bushu},sync_daytime='${user.sync_daytime}' where user_id = ${user.user_id};`;
        return G.dbUtils.run(sql);
    },

    // 归档
    placeOn(user,dayStamp){
        let sql = `insert into data_bushu (user_id,bushu,daytime) values (${user.user_id},${user.bushu},'${dayStamp}');`;
        return G.dbUtils.run(sql);
    }
};
userController.login = async ctx => {
    let query = ctx.query;
    logger.info("query:", JSON.stringify(query));

    // 参数检查
    if(checkDeviceId(ctx)){
        return;
    }

    if(checkSysBushu(ctx)){
        return;
    }

    let sysBushu = Number(query.sys_bushu);

    // 每个用户登陆的时候, reqId 初始化为1.
    // 每次同步步数的时候,都需要传递 reqId
    // let reqId = 1;
    let user = await userController.findUser(query.device_id);
    if (user) {
        // 判断用户当前是否需要更新数据
        await checkBushu(user,sysBushu);

        ctx.body = G.msgUtils.makeSuccessObj({
            user:user,
        });
    } else {

        let sysBushu = Number(query.sys_bushu);

        // 新用户 不存在归档
        await userController.newUser(query.device_id, sysBushu);
        user = await userController.findUser(query.device_id);
        logger.info("user:" + JSON.stringify(user));
        ctx.body = G.msgUtils.makeSuccessObj({
            user:user,
        });
    }
};


// 同步步数
userController.sync = async ctx => {
    let query = ctx.query;
    logger.info("query:", JSON.stringify(query));

    if(checkUserId(ctx)){
        return;
    }
    if(checkSysBushu(ctx)){
        return;
    }
    let userId = Number(query.user_id);
    logger.info("userId:" + userId);

    let sysBushu = Number(query.sys_bushu);
    logger.info("sysBushu:" + sysBushu);

    // 暂时不考虑请求顺序问题

    // 更新步数
    let user = await userController.findUserByUserId(userId);
    await checkBushu(user,sysBushu);
    logger.info("user:" + JSON.stringify(user));
    ctx.body = G.msgUtils.makeSuccessObj({
        user:user
    });
};

// function checkReqId(ctx) {
//     if (!ctx.query.req_id) {
//         logger.info('确少参数req_id');
//         ctx.body = G.msgUtils.makeErrObj(G.MSG_PARAM_ERROR,'确少参数req_id');
//         return true;
//     }
//     let reqId = Number(ctx.query.req_id);
//     if(isNaN(reqId)){
//         logger.info('reqId 应该为number.');
//         ctx.body = G.msgUtils.makeErrObj(G.MSG_TYPE_ERROR,'reqId 应该为number.');
//         return true;
//     }
//     return false;
// }

function checkUserId(ctx){
    if (!ctx.query.user_id) {
        logger.info('确少参数user_id');
        ctx.body = G.msgUtils.makeErrObj(G.MSG_PARAM_ERROR,'确少参数user_id');
        return true;
    }
    let userId = Number(ctx.query.user_id);
    if(isNaN(userId)){
        logger.info('user_id 应该为number.');
        ctx.body = G.msgUtils.makeErrObj(G.MSG_TYPE_ERROR,'user_id 应该为number.');
        return true;
    }
    return false;
}

function checkDeviceId(ctx){
    if (!ctx.query.device_id) {
        logger.info('确少参数 device_id.');
        ctx.body = G.msgUtils.makeErrObj(G.MSG_PARAM_ERROR, '确少参数 device_id.');
        return true;
    }
    return false;
}

function checkSysBushu(ctx){
    if (!ctx.query.sys_bushu) {
        logger.info('确少参数 sys_bushu');
        ctx.body = G.msgUtils.makeErrObj(G.MSG_PARAM_ERROR, '确少参数 sys_bushu');
        return true;
    }

    let sysBushu = Number(ctx.query.sys_bushu);
    if (isNaN(sysBushu)) {
        logger.info('sys_bushu 应该为数字');
        ctx.body = G.msgUtils.makeErrObj(G.MSG_TYPE_ERROR, 'sys_bushu 应该为数字');
        return true;
    }

    return false;
}

async function checkBushu(user,curSysBuShu){

    let curDayStamp = G.getDayStamp();

    // 进行更新和归档
    if(user.sync_daytime !== curDayStamp){
        // 需要归档
        // 更新玩家当前步数
        refreshUserBuShu(user,curSysBuShu);

        logger.info("进行归档. user:",JSON.stringify(user));

        // 需要进行归档
        // 归档日期为 lastDayStamp
        userController.placeOn(user,user.sync_daytime);
        user.bushu = 0;
        user.sync_daytime = curDayStamp;

        // 更新玩家数据
        logger.info("更新玩家步数!");
        await userController.updateUserBuShu(user);
    }else{
        // 不需要归档
        let refreshed = refreshUserBuShu(user,curSysBuShu);
        if(refreshed){
            logger.info("更新玩家步数!");
            await userController.updateUserBuShu(user);
        }
    }
}

/**
 *
 * @param user
 * @param curSysBuShu
 * @return {boolean} true 表示产生了更新,后续操作需要更新数据库
 */
function refreshUserBuShu(user,curSysBuShu){
    if(user.sys_bushu > curSysBuShu){
        // 认为重启过
        user.bushu += curSysBuShu;
        user.sys_bushu = curSysBuShu;
        return true;
    }else{
        // 没有重启,直接更新
        if(curSysBuShu === user.sys_bushu){
            // 减少数据库操作
            return false;
        }

        user.bushu += (curSysBuShu - user.sys_bushu);
        user.sys_bushu = curSysBuShu;
        return true;
    }
}


module.exports = userController;
